package com.security.customer.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;

/**
 * @Author: TongRui乀
 * @Date: 2020-04-06 10:07
 * @description： 权限认证失败的处理器
 */
@Slf4j
@Component
public class CustomerAccessDeniedHandler implements AccessDeniedHandler {

    private ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException e) throws IOException, ServletException {

        log.info("权限认证失败：{}", e.getMessage());

        HashMap<String, String> result = new HashMap<String, String>();

        result.put("code", "1003");
        result.put("message", "权限认证失败, 您无权此操作！");

        response.setContentType("application/json;charset=utf-8");
        response.getOutputStream().write(objectMapper.writeValueAsBytes(result));

    }
}
